package org.hyperzsoft.one;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.hyperzsoft.UserTask;
import org.hyperzsoft.utilities;
import org.hyperzsoft.com.R;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class main extends Activity {
	private static final String TAG = "OnE";
	private GetDataTask mGetData;
	
    private static final String STATE_GET_DATA_IN_PROGRESS = "main.get.data.inprogress";
    private static final String STATE_GET_DATA_TYPE = "main.get.data";
	
    private Bundle mSavedState;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        onImport();
    }
    
    private void onImport() {
        if (mGetData == null || mGetData.getStatus() == UserTask.Status.FINISHED) {
        	mGetData = (GetDataTask) new GetDataTask().execute();
        } else {
            utilities.showToast(this, R.string.error_import_in_progress);
        }
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.main_menu, menu);
			return true;
		} catch (Exception e) {
			Log.e(TAG, e.getMessage().toString());
			for (StackTraceElement traceElement : e.getStackTrace()) {
				Log.e(TAG, "  at " + traceElement.toString());
			}
			return false;
		}
	}
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent myIntent = new Intent();
		
		try {
			if (item.getItemId() == R.id.menu_item_1) {
				startActivity(myIntent);
				return true;
			} else {
				return super.onOptionsItemSelected(item);
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage().toString());
			for (StackTraceElement traceElement : e.getStackTrace()) {
				Log.e(TAG, "  at " + traceElement.toString());
			}
			return false;
		}
	}
    
    @Override
    protected void onResume() {
        super.onResume();
        if (mSavedState != null) restoreLocalState(mSavedState);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        onCancelGetData();
        
    }
    
    private void onCancelGetData() {
        if (mGetData != null && mGetData.getStatus() == UserTask.Status.RUNNING) {
        	mGetData.cancel(true);
        	mGetData = null;
        }
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        restoreLocalState(savedInstanceState);
        mSavedState = null;
    }
    
    private void restoreLocalState(Bundle savedInstanceState) {
        restoreTask(savedInstanceState);
    }
    
    private void restoreTask(Bundle savedInstanceState) {
        if (savedInstanceState.getBoolean(STATE_GET_DATA_IN_PROGRESS)) {
            final String id = savedInstanceState.getString(STATE_GET_DATA_TYPE);
            
            mGetData = (GetDataTask) new GetDataTask().execute(id);
        }
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	saveTask(outState);
    }
    
    private void saveTask(Bundle outState) {
    	final GetDataTask task = mGetData;
    	if (task != null && task.getStatus() != UserTask.Status.FINISHED) {
    		
    		task.cancel(true);
    	}
    }
    
    private class GetDataTask extends UserTask<String, Integer, Void> {
    	@Override
        public void onPreExecute() {
    		((ProgressBar) findViewById(R.id.progress)).setIndeterminate(true);
    		
            final View cancelButton = findViewById(R.id.button_cancel);
            cancelButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                	onCancelGetData();
                }
            });
    	}
    	
    	@Override
        public void onCancelled() {
    		
    	}
    	
    	@Override
    	public Void doInBackground(String... params) {
			long timing;
			ArrayList<Team> teams = new ArrayList<Team>();
			Calendar cal = Calendar.getInstance();
			
			timing = cal.getTimeInMillis();
			
			cal.roll(Calendar.DATE, true);
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
			
			Document doc = utilities.getDocument("http://www.nhl.com/ice/standings.htm", 
					"date", sdf.format(cal.getTime()), "season", 
					utilities.getSeasonValue(), "type", "LEA");
			
			Element standings = doc.body().select("tbody").get(2);
			
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					((TextView) findViewById(R.id.label_import)).setText(
                    	"Get & Parse of Standings complete, Starting team data build...");
				}
			});
			
			for (Element teamRow : standings.select("tr")) {
				if (isCancelled()) return null;
				final Team currTeam = new Team();
				currTeam.BuildTeamFromNode(teamRow);
				teams.add(currTeam);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						((TextView) findViewById(R.id.label_import)).setText(
								"Data built for " + currTeam.getFullName() + ", moving to next team...");
					}
				});
			}
			
			cal = Calendar.getInstance();
			final long finalTiming = cal.getTimeInMillis() - timing;
			
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(main.this, "Built standings in " + finalTiming + " msecs", Toast.LENGTH_LONG).show();
				}
			});
			
    		return null;
    	}
    	
    	@Override
        public void onPostExecute(Void result) {
    		
    	}
    }
}